package edu.zjut.hjg.saas.kwmp.web.controller.teacher;

import static edu.zjut.hjg.saas.kwmp.web.support.KwmpConstants.SESSION_NAME_USER;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.document.AbstractJExcelView;

import edu.zjut.hjg.saas.biz.model.Baby;
import edu.zjut.hjg.saas.biz.model.Kindergarten;
import edu.zjut.hjg.saas.biz.model.SchoolClass;
import edu.zjut.hjg.saas.biz.service.BabyService;
import edu.zjut.hjg.saas.biz.service.SchoolClassService;
import edu.zjut.hjg.saas.common.annotation.CookieSessionIn;
import edu.zjut.hjg.saas.common.annotation.RequestAttribute;
import edu.zjut.hjg.saas.common.util.ParameterUtil;
import edu.zjut.hjg.saas.kwmp.web.model.UserSession;

@Controller
@RequestMapping("/teacher/baby")
public class BabyManageController {
    private static final Log   log = LogFactory.getLog(BabyManageController.class);

    @Autowired
    private BabyService        babyService;

    @Autowired
    private SchoolClassService schoolClassService;

    @RequestMapping("index.htm")
    public String index(@RequestAttribute Kindergarten app, Model model) {
        model.addAttribute("babies", babyService.listAllByAppId(app.getId()));
        List<SchoolClass> schoolClasses = schoolClassService.listByAppId(app.getId());
        if (schoolClasses.isEmpty()) {
            SchoolClass schoolClass = new SchoolClass();
            schoolClass.setId(-1);
            schoolClass.setKindergarten(app);
            schoolClass.setName("新建一个(默认班级)");
            schoolClasses.add(schoolClass);
        }
        model.addAttribute("schoolClasses", schoolClasses);
        return "teacher/baby";
    }

    @CookieSessionIn(value = SESSION_NAME_USER, param = "session")
    @RequestMapping(value = "create.htm", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> create(@RequestAttribute Kindergarten app, UserSession session,
                                      Baby baby) {
        Map<String, Object> result = new HashMap<String, Object>();
        if (!ParameterUtil.notBlank(baby)) {
            result.put("success", false);
            result.put("message", "参数错误");
            return result;
        }
        baby.setKindergarten(app);
        try {
            babyService.create(baby, session.getLoginId());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.put("success", false);
            result.put("message", "添加宝宝失败");
            return result;
        }
        result.put("success", true);
        result.put("baby", baby);
        return result;
    }

    @CookieSessionIn(value = SESSION_NAME_USER, param = "session")
    @RequestMapping("delete.htm")
    @ResponseBody
    public Map<String, Object> delete(@RequestAttribute Kindergarten app, UserSession session,
                                      @RequestParam("id") int id) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            babyService.deleteByIdAndAppId(id, app.getId(), session.getLoginId());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.put("success", false);
            result.put("message", "删除宝宝失败");
            return result;
        }
        result.put("success", true);
        return result;
    }

    @CookieSessionIn(value = SESSION_NAME_USER, param = "session")
    @RequestMapping(value = "update.htm", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> update(@RequestAttribute Kindergarten app, UserSession session,
                                      Baby baby) {
        Map<String, Object> result = new HashMap<String, Object>();
        if (baby == null) {
            result.put("success", false);
            result.put("message", "参数错误");
            return result;
        }
        baby.setKindergarten(app);
        try {
            babyService.update(baby, app.getId(), session.getLoginId());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.put("success", false);
            result.put("message", "更新宝宝失败");
            return result;
        }
        result.put("success", true);
        return result;
    }

    @RequestMapping("report.htm")
    public ModelAndView report(@RequestAttribute Kindergarten app) {
        List<Baby> babies = babyService.listAllByAppId(app.getId());
        return new ModelAndView(new ReportView(), "babies", babies).addObject("appName", app
                .getName());
    }

    public class ReportView extends AbstractJExcelView {

        @SuppressWarnings("unchecked")
        @Override
        protected void buildExcelDocument(Map<String, Object> model, WritableWorkbook workbook,
                                          HttpServletRequest request, HttpServletResponse response)
                throws Exception {
            response.addHeader("Content-Disposition", "attachment; filename=report.xls");
            List<Baby> babies = (List<Baby>) model.get("babies");
            String appName = (String) model.get("appName");
            WritableSheet sheet = workbook.createSheet("宝宝名单", 0);
            sheet.addCell(new Label(0, 0, appName));
            sheet.mergeCells(0, 0, 5, 0);

            sheet.addCell(new Label(0, 1, "序号"));
            sheet.addCell(new Label(1, 1, "姓名"));
            sheet.addCell(new Label(2, 1, "年龄"));
            sheet.addCell(new Label(3, 1, "父(母)"));
            sheet.addCell(new Label(4, 1, "性别"));
            sheet.addCell(new Label(5, 1, "班级"));
            for (int i = 0; i < babies.size(); i++) {
                Baby baby = babies.get(i);
                sheet.addCell(new jxl.write.Number(0, i + 2, baby.getId()));
                sheet.addCell(new Label(1, i + 2, baby.getName()));
                sheet.addCell(new jxl.write.Number(2, i + 2, baby.getAge()));
                sheet.addCell(new Label(3, i + 2, baby.getParentName()));
                sheet.addCell(new Label(4, i + 2, baby.getGender().getName()));
                sheet.addCell(new Label(5, i + 2, baby.getSchoolClass().getName()));
            }
        }
    }
}
